package com.infore.airsupervise.other.listener;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**签名版 视图操作的业务  实现类
 * Created by xiaotao on 2017/5/17.
 */

public class SignatrueBizImpl implements SignatrueBiz {
    private String folderPath;

    public SignatrueBizImpl() {
        File folder = new File(Environment.getExternalStorageDirectory(),"com.infore.airsupervise/Picture/Signature");
        if(!folder.exists()){
            folder.mkdirs();
        }
        folderPath = folder.getAbsolutePath();
    }

    @Override
    public void ClearSignatrue(SignatrueViewListener signatrueViewListener) {
        signatrueViewListener.clearListener();
    }

    @Override
    public void SaveSignatrue(Bitmap signatureBitmap, SignatrueViewListener signatrueViewListener) {
        //保存签名到文件夹
        try {
            File photo = new File(folderPath, String.format("Signature_%d.jpg", System.currentTimeMillis()));
            // 记录下图片的路径
            String filePath = photo.getPath();
            saveBitmapToJPG(signatureBitmap, photo);
            signatrueViewListener.saveSuccess(filePath);
            //成功
        } catch (IOException e) {
            e.printStackTrace();
            signatrueViewListener.saveFailed();
        }

    }

    /**
     * 保存
     * @param bitmap
     * @param photo
     * @throws IOException
     */
    public void saveBitmapToJPG(Bitmap bitmap, File photo) throws IOException {
        Bitmap newBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawBitmap(bitmap, 0, 0, null);
        OutputStream stream = new FileOutputStream(photo);
        newBitmap.compress(Bitmap.CompressFormat.JPEG, 80, stream);
        stream.close();
    }



}
